<template>
  <div>
    <div class="mb15 lh1">请求模型</div>
    <div class="ks-row-middle mb20 lh1">
      <tree-select
        v-model="modelCode"
        class="mb10"
        placeholder="请选择业务模型"
        filterable
        :fieldMap="{
        value: 'code',
        label: 'name',
        disabled: 'disabled',
      }"
        :filterNodeMethod="filterNodeMethod"
        :treeData="modelList"
      />
    </div>
    <div class="mb15 lh1">请求业务服务</div>
    <div class="mb24">
      <el-select
          v-model="serviceId"
          placeholder="请选择业务服务"
          style="width: 100%"
      >
        <el-option
            :value="i.key"
            :label="`${i.name} （${i.key}）`"
            v-for="(i, index) in serviceList"
            :key="index"
        ></el-option>
      </el-select>
    </div>

    <div class="ks-row-between mb20 lh1">
      <span style="width: 100px">请求参数</span>
      <el-switch v-model="showParam" @change="changeShowParam" />
    </div>
      <div class="ks-row-between mb20 lh1">
        <span style="width: 100px">成功回调</span>
        <el-switch v-model="showSuccess" @change="changeShowSuccess" />
      </div>
      <div class="ks-row-between mb20 lh1">
        <span style="width: 100px">失败回调</span>
        <el-switch v-model="showError" @change="changeShowError" />
      </div>

  </div>
</template>

<script>
import Blockly from 'blockly'

import { getHmmodelfolderListTree } from '@/apis/paas/HmModelFolderController.js'
import { getHmhttprequestdefinitionList } from '@/apis/paas/HmHttpRequestDefinitionController.js'
import { filterNodeMethod } from "@/utils/treeSelectFormat";
import lodash from "lodash";
export default {
  name: 'ModalSelect',
  props: {
    eventItem: {}, // 需要逻辑编排的对象
    componentItem: {},
    block: {},
    workspace: {}
  },
  components: { },
  computed: {
    modelCode: {
      get() {
        const targetBlock = this.block.getInputTargetBlock('PARAM_MODEL')
        const modelCode = targetBlock?.getFieldValue('TEXT')
        return modelCode || ''
      },
      set(val) {
        this.handleAddModel(val)
      }
    },
    serviceId: {
      get(){
        const targetBlock = this.block.getInputTargetBlock('PARAM_API')
        const modelCode = targetBlock?.getFieldValue('TEXT')
        return modelCode || ''
      },
      set(val){
        this.handleAddService(val)
      }

    },
    requestParam: {
      get() {
        const count = this.block?.paramCount_
        this.showParam = count ? true : false
        return count ? true : false
      },
      set(val) {
        this.block.paramCount_ = val ? 1 : 0
        this.block.updateShape_()
      }
    },
    requestSuccess: {
      get() {
        const count = this.block?.successCount_
        this.showSuccess = count ? true : false
        return count ? true : false
      },
      set(val) {
        this.block.successCount_ = val ? 1 : 0
        this.block.updateShape_()
      }
    },
    requestError: {
      get() {
        const count = this.block?.errorCount_
        this.showError = count ? true : false
        return count ? true : false
      },
      set(val) {
        this.block.errorCount_ = val ? 1 : 0
        this.block.updateShape_()
      }
    }
  },
  data () {
    return {
      filterNodeMethod,
      formData: {},
      modelList: [], // 业务模型
      serviceList:[], // 业务服务
      showParam: false,
      showSuccess: false,
      showError: false
    }
  },
  async mounted() {
    var data = await getHmmodelfolderListTree();
    data.forEach((node) => {
      node.type = "folder";
    });
    this.modelList = this.createModelTreeNode(data);
  },
  watch: {
    'block': {
      handler() {
        this.getBlockData()
      },
      immediate: true
    },
    modelCode: {
      handler(val) {
        this.getModelId(val)
      },
      immediate: true
    },
  },
  methods: {
    getBlockData() {
      const paramCount = this.block?.paramCount_
      this.showParam = !!paramCount
      this.requestParam = !!paramCount

      const successCount = this.block?.successCount_
      this.showSuccess = !!successCount
      this.requestSuccess = !!successCount

      const errorCount = this.block?.errorCount_
      this.showError = !!errorCount
      this.requestError = !!errorCount

    },
    changeShowParam(val) {
      this.requestParam = val
    },
    changeShowSuccess(val){
      this.requestSuccess = val
    },
    changeShowError(val){
      this.requestError = val
    },

    handleAddModel(data) {
      const rootBlock = this?.workspace?.getBlockById(this.block.id) // input
      const connection = rootBlock.getInput(`PARAM_MODEL`).connection
      const oldBlock = rootBlock.getInputTargetBlock('PARAM_MODEL')
      const newBlock = this.workspace.newBlock('text')
      newBlock.setFieldValue(data, 'TEXT')
      newBlock.setEditable(false)
      newBlock.setDeletable(false)
      newBlock.setMovable(false)
      connection.connect(newBlock.outputConnection)
      if(oldBlock){
        oldBlock.dispose()
      }
      this.block.updateShape_()
      this.updateWorkspaceWithXml()
    },
    handleAddService(data) {
      const rootBlock = this?.workspace?.getBlockById(this.block.id) // input
      const connection = rootBlock.getInput(`PARAM_API`).connection
      const oldBlock = rootBlock.getInputTargetBlock('PARAM_API')
      const newBlock = this.workspace.newBlock('text')
      newBlock.setFieldValue(data, 'TEXT')
      newBlock.setEditable(false)
      newBlock.setDeletable(false)
      newBlock.setMovable(false)
      connection.connect(newBlock.outputConnection)
      if(oldBlock){
        oldBlock.dispose()
      }
      this.block.updateShape_()
      this.updateWorkspaceWithXml()
    },
    updateWorkspaceWithXml() {
      const xml = Blockly.Xml.workspaceToDom(this.workspace)
      Blockly.Xml.clearWorkspaceAndLoadFromXml(xml, this.workspace)
    },
    createModelTreeNode(tree) {
      return lodash.cloneDeep(tree).map((node) => {
        node.disabled = node.type === "folder";
        if (node.modelResults) {
          node.id = "folder" + node.id;
          node.children = node.modelResults || [];
          node.children.forEach((item) => {
            item.name = `${item.name}(${
              item.supportProcess ? "流程模型" : "表单模型"
            })(${item.type})`;
          });
        }
        return node;
      });
    },
    async getServiceList() {
      if(!this.modelId) return
      this.serviceList = await getHmhttprequestdefinitionList({
        modelId: this.modelId,
      });
    },
    async getModelId(val){
      if(!val) return
      if(!this.modelList?.length){
        var data = await getHmmodelfolderListTree();
        data.forEach((node) => {
          node.type = "folder";
        });
        this.modelList = this.createModelTreeNode(data);
      }
      let modelId = "";
      this.modelList.forEach((folder) => {
        const children = folder.modelResults || [];
        children.forEach((item) => {
          if (item.code === val) {
            modelId = item.id;
          }
        });
      });
      this.modelId = modelId;
      this.getServiceList()
    }
  }
}
</script>

<style scoped>

</style>
